package com.shire.shire_interface.service.rule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.constants.Constants;
import com.shire.shire_interface.constants.WxConstants;
import com.shire.shire_interface.constants.WxErrorCode;
import com.shire.shire_interface.dao.rule.WxRuleGroupDao;
import com.shire.shire_interface.dao.rule.WxRuleRecordDao;
import com.shire.shire_interface.model.cs.WxChat;
import com.shire.shire_interface.model.friend.WxFriend;
import com.shire.shire_interface.model.group.WxGroup;
import com.shire.shire_interface.model.rule.WxRuleGroup;
import com.shire.shire_interface.model.rule.WxRuleGroupExample;
import com.shire.shire_interface.model.rule.WxRuleRecord;
import com.shire.shire_interface.model.rule.WxRuleRecordExample;
import com.shire.shire_interface.model.user.WxAccount;
import com.shire.shire_interface.service.chat.WxChatService;
import com.shire.shire_interface.service.friend.WxFriendService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class WxRuleGroupService {
    @Resource
    private WxRuleGroupDao wxRuleGroupDao;
    @Resource
    private WxRuleRecordDao ruleRecordDao;

    @Resource
    private WxFriendService friendService;

    @Resource
    private WxChatService chatService;

    public static final String DISSMISS_RET = "$dismiss$";

    public int insert(WxRuleGroup wxRuleGroup) {
        return wxRuleGroupDao.insertSelective(wxRuleGroup);
    }

    public List<WxRuleGroup> selectByExample(WxRuleGroupExample example) {
        return wxRuleGroupDao.selectByExample(example);
    }

    public int deleteByPrimaryKey(Integer taskId) {
        return wxRuleGroupDao.deleteByPrimaryKey(taskId);
    }

    public String checkRule(WxAccount account, WxChat chat, WxGroup group) {
        WxRuleGroupExample example = new WxRuleGroupExample();
        example.createCriteria();
        if (chat.getRealFromWxId() == null)
            return null;

        List<WxRuleGroup> groupRules = wxRuleGroupDao.selectByExample(example);
        if (groupRules == null || groupRules.size() < 1)
            return null;

        WxRuleGroup rule = groupRules.get(0);

        JSONObject jsonObject = JSONObject.parseObject(rule.getRulejson());

        //不包含帐号
        if (rule.getWxaccounts() == null || !rule.getWxaccounts().contains(account.getWxid()))
            return null;

        //白名单
        if (chat.getRealFromWxId() == null
                && jsonObject.containsKey("whiteList")
                && jsonObject.getJSONArray("whiteList").contains(chat.getRealFromWxId()))
            return null;

        boolean flag = false;
        String breakRule = null;

        JSONObject keyWordObject = null;
        if (jsonObject.containsKey("keywords"))
            keyWordObject = jsonObject.getJSONObject("keywords");
        if (!flag && jsonObject.containsKey("adSetting") && jsonObject.getJSONArray("adSetting").size()>0) {
            if (keyWordObject.containsKey("nickname")) {
                for (Object tmp : keyWordObject.getJSONArray("nickname")) {
                    if (StringUtils.isNotBlank((String) tmp) && chat.getRealFromNick().contains((String) tmp)) {
                        breakRule = "nickname";
                        flag = true;
                        break;
                    }
                }
            }
        }
        WxConstants.MessageType msgType = WxConstants.MessageType.get(chat.getMsgtype());
        JSONArray addSetting = jsonObject.getJSONArray("adSetting");
        if (!flag && jsonObject.containsKey("adSetting") && jsonObject.getJSONArray("adSetting").size()>0) {

            switch (msgType) {
                case TEXT: {
                    JSONObject chatJson = JSONObject.parseObject(chat.getContent());
                    if (jsonObject.containsKey("maxLine") && jsonObject.getInteger("maxLine") != null) {
                        if (chatJson.getString("content").split("\\n").length > jsonObject.getInteger("maxLine")) {
                            breakRule = "maxLine";
                            break;
                        }
                    }
                    if (jsonObject.containsKey("maxCount") && jsonObject.getInteger("maxCount") != null) {
                        if (chatJson.getString("content").length() > jsonObject.getInteger("maxCount")) {
                            breakRule = "maxCount";
                            break;
                        }
                    }

                    if (keyWordObject.containsKey("message")) {
                        for (Object tmp : keyWordObject.getJSONArray("message")) {
                            if (chatJson.getString("content").contains((String) tmp)) {
                                breakRule = "message";
                                flag = true;
                                break;
                            }
                        }
                    }
                }
                break;
                case FRIEND_CARD:
                    if (addSetting.contains("card")){
                        breakRule = "card";
                    }
                    break;
                case FILE:
                    if (addSetting.contains("file")){
                        breakRule = "file";
                    }
                    break;
                case VIDEO:
                    if (addSetting.contains("video")){
                        breakRule = "video";
                    }
                    break;
                case MINI_PROGRAM:
                    if (addSetting.contains("miniprogram")){
                        breakRule = "miniprogram";
                    }
                    break;
                case LINK_CARD:
                    if (addSetting.contains("linkshare")){
                        breakRule = "linkshare";
                    }
                    break;
                default:
                    break;
            }
        }

        if (msgType == WxConstants.MessageType.TEXT && jsonObject.containsKey("notifyAdmin") && jsonObject.getBoolean("notifyAdmin")){
            String adminWxid = jsonObject.getString("adminWxId");
            String notifyKeywords = jsonObject.getString("notifyKeywords");
            WxFriend admin = friendService.getFriendByWxId(account.getCsid(),account.getWxid(),adminWxid);
            if (admin != null){
                JSONObject chatJson = JSONObject.parseObject(chat.getContent());
                String content = chatJson.getString("content");
                String[] keys = notifyKeywords.split(",");
                for (int i = 0; i < keys.length; i++){
                    String k = keys[i];
                    if (StringUtils.isNotBlank(k)){
                        if (content.contains(k)){
                            WxChat noticeChat = new WxChat();
                            JSONObject sendContent = new JSONObject();

                            StringBuilder warningContent = new StringBuilder();
                            warningContent.append("【");
                            warningContent.append(group.getGroupname());
                            warningContent.append("】");
                            warningContent.append(System.lineSeparator());
                            warningContent.append("发送人：");
                            warningContent.append(chat.getRealFromNick());
                            warningContent.append("(");
                            warningContent.append(chat.getRealFromWxId());
                            warningContent.append(")");
                            warningContent.append(System.lineSeparator());
                            warningContent.append("--------------");
                            warningContent.append(System.lineSeparator());
                            warningContent.append(content);

                            sendContent.put("msgtype", 1);
                            sendContent.put("content", warningContent.toString());
                            noticeChat.setWxaccount(account.getWxid());
                            noticeChat.setMsgid(String.valueOf((new Date()).getTime()));
                            noticeChat.setFriendwxid(admin.getFriendwxid());
                            noticeChat.setFriendNick(admin.getFriendnick());
                            noticeChat.setAvatar(admin.getAvatar());
                            noticeChat.setChatfrom(WxConstants.ChatFrom.SELF.getCode());
                            noticeChat.setContent(sendContent.toJSONString());
                            noticeChat.setMsgtype(WxConstants.MessageType.TEXT.getCode());
                            noticeChat.setSendstatus(WxErrorCode.INIT_VALUE);
                            noticeChat.setReadstatus(Constants.YesNo.YES.ordinal());
                            noticeChat.setFromplat(0);
                            noticeChat.setShowstatus(Constants.YesNo.YES.getCode());
                            noticeChat.setCsid(account.getCsid());
                            noticeChat.setCreatetime(new Date());
                            noticeChat.setReadtime(new Date());
                            chatService.sendChatByCmd(noticeChat);
                            chatService.sendToKf(noticeChat, admin);
                            break;
                        }
                    }
                }
            }
        }

        if (StringUtils.isNotBlank(breakRule)){
            WxRuleRecord record = getRuleRecord(account, chat);
            if (record.getRulebroken() == null){
                record.setRulebroken(breakRule);
            }else {
                record.setRulebroken(record.getRulebroken()+","+breakRule);
            }

            if (jsonObject.containsKey("type")&& jsonObject.getString("type").equals("dismiss")){
                record.setType(1);
            }else {
                if (jsonObject.containsKey("warnTimes") && jsonObject.getInteger("warnTimes") <= record.getWarningcount()){
                    record.setType(1);
                }else {
                    record.setType(0);
                    record.setWarningcount(record.getWarningcount() + 1);
                }
            }

            record.setGroupno(group.getGroupno());
            record.setGroupname(group.getGroupname());
            record.setGroupavatar(group.getAvatar());
            record.setGroupmembernick(chat.getRealFromNick());
            record.setGroupmemberavatar(chat.getRealFromHeadImg());


            if (record.getId() == null){
                ruleRecordDao.insert(record);
            }else {
                ruleRecordDao.updateByPrimaryKey(record);
            }

            //TODO: 踢人指令
            if (record.getType() == 1){
                return DISSMISS_RET;
            }else{
                //TODO 发出警告
                return jsonObject.getString("warnContent");
            }
        }
        return null;
    }

    private WxRuleRecord getRuleRecord(WxAccount account, WxChat chat){
        WxRuleRecordExample example = new WxRuleRecordExample();
        example.createCriteria()
                .andGroupnoEqualTo(chat.getFriendwxid())
                .andWxaccountEqualTo(account.getWxid())
                .andGroupmemberidEqualTo(chat.getRealFromWxId());
        List<WxRuleRecord> ruleRecords = ruleRecordDao.selectByExample(example);
        if (ruleRecords == null || ruleRecords.size()<1){
            WxRuleRecord record = new WxRuleRecord();
            record.setCreateTime(new Date());
            record.setWxaccount(account.getWxid());
            record.setWarningcount(0);
            record.setCsid(account.getCsid());
            record.setGroupmemberid(chat.getRealFromWxId());
            record.setGroupno(chat.getFriendwxid());
            return record;
        }

        return ruleRecords.get(0);
    }

    public int insertSelective(WxRuleGroup wxRuleGroup) {
        return wxRuleGroupDao.insertSelective(wxRuleGroup);
    }

    public int updateByExampleSelective(WxRuleGroup wxRuleGroup, WxRuleGroupExample wxRuleGroupExample) {
        return wxRuleGroupDao.updateByExampleSelective(wxRuleGroup,wxRuleGroupExample);
    }
}
